var express = require('express');
var router = express.Router();
const bcrypt = require('bcryptjs');
var { User } = require('../model/db');
const SMSClient = require('@alicloud/sms-sdk');
const { format } = require('date-fns');
const codeMap = new Map(); // 在文件顶部定义

const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'travelApp'; // 替换为实际数据库名
let db;

(async () => {
  try {
    const client = await MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
    db = client.db(dbName);
    console.log('MongoDB connected successfully');
  } catch (err) {
    console.error('MongoDB connection error:', err.stack);
    process.exit(1);
  }
})();

// require('dotenv').config();
/* GET home page. */

// 配置阿里云 SMS (正式环境)
const smsClient = new SMSClient({
  accessKeyId: 'LTAI5tPGFw79r4VMQD98wTnA',
  secretAccessKey: 'z0ZTu4xC8kTj7XkZmyqRLURpJpgCV9',
  endpoint: 'dysmsapi.aliyuncs.com',
});



//登录
router.post('/login', async (req, res) => {
  const { username, password } = req.body;

  try {
    const user = await User.findOne({ username });
    if (!user) {
      return res.json({ success: false, message: '用户名或密码错误' });
    }

    // 使用 bcrypt 比较输入的密码与数据库中的哈希密码
    const isMatch = await bcrypt.compare(password, user.password);
    if (isMatch) {
      res.json({ success: true, id: user._id });
    } else {
      res.json({ success: false, message: '用户名或密码错误' });
    }
  } catch (error) {
    console.error('Login error:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 获取个人资料
router.get('/profile/:id', async (req, res) => {
  try {
    const user = await User.findOne({ _id: req.params.id });
    if (!user) {
      return res.status(404).json({ success: false, message: '用户不存在' });
    }
    res.json({
      ...user.toObject(),
      birthday: user.birthday ? format(user.birthday, 'yyyy年M月d日') : '',
    });
  } catch (error) {
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 获取用户数据
router.get('/getuserdata/:id', async (req, res) => {
  const user = await User.findOne({ _id: req.params.id });
  if (!user) {
    return res.status(404).json({ success: false, message: '用户数据不存在' });
  }
  res.json({
    success: true,
    data: user
  })
})

//修改数据
router.post('/update-profile/:id', async (req, res) => {
  try {
    const { surname, name, username, phone, email, birthday, gender, background, avatar } = req.body;

    const user = await User.findOne({ _id: req.params.id });
    if (!user) {
      return res.status(404).json({ success: false, message: '用户不存在' });
    }

    // 验证唯一性
    // const existingUser = await User.findOne({
    //   $or: [{ surname }, { name }, { username }, { email }, { phonenumber: phone }],
    //   _id: { $ne: user._id },
    // });
    // if (existingUser) {
    //   return res.status(400).json({ success: false, message: '姓、名、用户名、邮箱或电话已存在' });
    // }

    user.surname = surname;
    user.name = name;
    user.username = username;
    user.phonenumber = phone;
    user.email = email;
    user.birthday = new Date(birthday);
    user.gender = parseInt(gender, 10);
    user.background = background;
    user.avatar = avatar;

    await user.save();
    res.json({ success: true, message: '个人资料更新成功' });
  } catch (error) {
    console.error('错误:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});
// 更改密码 API
router.post('/change-password/:id', async (req, res) => {
  try {
    const { oldPassword, newPassword } = req.body;
    console.log('Received request for userId:', req.params.id);
    console.log('Received passwords:', { oldPassword, newPassword });

    const user = await User.findOne({ _id: req.params.id });
    if (!user) {
      console.log('User not found for id:', req.params.id);
      return res.status(404).json({ success: false, message: '用户数据不存在' });
    }

    const isMatch = await bcrypt.compare(oldPassword, user.password);
    if (!isMatch) {
      console.log('Old password mismatch for user:', req.params.id);
      return res.status(400).json({ success: false, message: '旧密码错误' });
    }
    // const isMatch = (oldPassword === user.password);
    // if (!isMatch) {
    //   console.log('Old password mismatch for user:', req.params.id);
    //   return res.status(400).json({ success: false, message: '旧密码错误' });
    // }

    if (newPassword.length < 6) {
      return res.status(400).json({ success: false, message: '新密码必须至少6个字符' });
    }
    const uniqueChar = newPassword.split('').some(char => /[#!@$%^&*]/.test(char));
    if (!uniqueChar) {
      return res.status(400).json({ success: false, message: '新密码必须包含一个独特的字符，如@、#、$;等' });
    }

    const hashedPassword = await bcrypt.hash(newPassword, 10);
    user.password = hashedPassword;
    await user.save();

    res.json({ success: true, message: '密码已成功修改' });
  } catch (error) {
    console.error('错误:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});


// 验证码接口
router.get('/code', function (req, res) {
  const phoneNum = req.query.phoneNum;
  if (!phoneNum || !/^\d{11}$/.test(phoneNum)) {
    return res.status(400).send({ msg: '无效的手机号' });
  }
  const code = String(Math.floor(100000 + Math.random() * 900000));
  try {
    codeMap.set(phoneNum, code);
    console.log(`Stored code for ${phoneNum}: ${code}, codeMap size: ${codeMap.size}`);
    console.log('codeMap content:', [...codeMap.entries()]);
  } catch (err) {
    console.error('Error setting codeMap:', err.stack);
    return res.status(500).send({ msg: '验证码存储失败', error: err.message });
  }
  smsClient.sendSMS({
    PhoneNumbers: phoneNum,
    SignName: 'erdai712',
    TemplateCode: 'SMS_476515163',
    TemplateParam: `{"code": "${code}"}`
  }).then(function (response) {
    console.log('SMS response:', response);
    if (response.Code === 'OK') {
      res.send({ msg: 'ok', code });
    } else {
      res.status(500).send({ msg: 'fail', response });
    }
  }).catch(function (err) {
    console.error('SMS error:', err);
    res.status(500).send({ msg: 'fail', error: err.message });
  });
});

// 重置密码接口
router.post('/reset-password', async function (req, res) {
  try {
    const { phoneNum, code, newPassword } = req.body;
    console.log('Received request:', { phoneNum, code, newPassword });

    // 基本验证
    if (!phoneNum || !code || !newPassword) {
      return res.status(400).json({ success: false, message: '缺少必要参数' });
    }
    if (newPassword.length < 6) {
      return res.status(400).json({ success: false, message: '新密码长度不足6位' });
    }

    // 验证码验证
    const savedCode = codeMap.get(phoneNum);
    if (!savedCode || String(savedCode) !== String(code)) {
      console.log('Verification failed:', { savedCode, receivedCode: code });
      return res.status(400).json({ success: false, message: '验证码错误或已失效' });
    }

    // 使用 User 模型更新密码
    const normalizedPhoneNum = phoneNum.trim();
    let user = await User.findOne({ phonenumber: normalizedPhoneNum });
    if (!user) {
      // 如果用户不存在，创建新用户
      user = new User({ phonenumber: normalizedPhoneNum, password: newPassword });
    } else {
      // 加密新密码
      const hashedPassword = await bcrypt.hash(newPassword, 10);
      user.password = hashedPassword;
    }
    await user.save();

    // 清除验证码
    codeMap.delete(phoneNum);
    res.json({ success: true, message: '密码修改成功' });
  } catch (error) {
    console.error('Error:', error.stack);
    res.status(500).json({ success: false, message: '服务器错误', error: error.message });
  }
});
module.exports = router;
